﻿//*********************************************************************
//
//  文件名：PaymentService
//
//  作者： LW
//
//  作用：
//
//  日期：2015/9/24 10:27:09
//
//*********************************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YouTravel.DomainModels;
using YouTravel.ViewModels;
using YouTravel.QueryModels;
using EntityFramework.Data.Core;
using IRepositories.Core;
using Framework.Common.Paged;
using System.Data.Entity;
using Framework.Common.Exceptions;
using YouTravel.Framework.Enums;
using Framework.Common;
using YouTravel.Framework.ResourceMessage;
using YouTravel.Framework.Const;

namespace YouTravel.DomainService
{
    /// <summary>
    /// PaymentService
    /// 付款管理
    /// </summary>
    public class PaymentService : IPaymentService
    {
        //打印>条形码Header
        private const string PRINTBARCODEHEADER = "YTDJ";

        private readonly IEFRepository<Payment> _paymentRepository;
        private readonly IEFRepository<User> _userRepository;
        private readonly IEFRepository<SellerSupplier> _sellerSupplierRepository;
        private readonly IEFRepository<Contract> _contractRepository;
        private readonly IEFRepository<Special> _specialMainRepository;
        private readonly IEFRepository<Debit> _debitRepository;
        private readonly IEFRepository<Deduction> _deductionRepository;
        IUnitOfWork _db;

        public PaymentService(IUnitOfWork db,
          IEFRepository<Payment> paymentRepository,
          IEFRepository<User> userRepository,
          IEFRepository<SellerSupplier> sellerSupplierRepository,
          IEFRepository<Contract> contractRepository,
          IEFRepository<Special> specialMainRepository,
          IEFRepository<Debit> debitRepository,
          IEFRepository<Deduction> deductionRepository)
        {
            this._paymentRepository = paymentRepository;
            this._userRepository = userRepository;
            this._sellerSupplierRepository = sellerSupplierRepository;
            this._contractRepository = contractRepository;
            this._specialMainRepository = specialMainRepository;
            this._debitRepository = debitRepository;
            this._deductionRepository = deductionRepository;

            this._paymentRepository.SetDbContext(db);
            this._userRepository.SetDbContext(db);
            this._sellerSupplierRepository.SetDbContext(db);
            this._contractRepository.SetDbContext(db);
            this._specialMainRepository.SetDbContext(db);
            this._debitRepository.SetDbContext(db);
            this._deductionRepository.SetDbContext(db);
            this._db = db;
        }

        #region this class public
        /// <summary>
        /// 绑定查询条件
        /// </summary>
        /// <param name="queryCond"></param>
        /// <returns></returns>
        private Func<IQueryable<Payment>, IQueryable<Payment>> BuildQueryCondition(PaymentQuery queryCond)
        {
            return (query) =>
            {
                if (queryCond != null)
                {
                    if (queryCond.ApplyStartTime.HasValue && queryCond.ApplyEndTime.HasValue)
                    {
                        if (queryCond.ApplyStartTime.Value > queryCond.ApplyEndTime.Value)
                            throw new DataValidationException("结束日期需大于开始时间");
                        query = query.Where(c => c.ApplicationTime >= queryCond.ApplyStartTime.Value && c.ApplicationTime <= queryCond.ApplyEndTime.Value);
                    }
                    else
                    {
                        if (queryCond.ApplyStartTime.HasValue)
                        {
                            query = query.Where(c => c.ApplicationTime >= queryCond.ApplyStartTime.Value);
                        }
                        if (queryCond.ApplyEndTime.HasValue)
                        {
                            query = query.Where(c => c.ApplicationTime <= queryCond.ApplyEndTime.Value);
                        }
                    }
                    if (queryCond.Status.HasValue)
                        query = query.Where(c => c.Status == queryCond.Status);
                    if (!string.IsNullOrWhiteSpace(queryCond.SpecialName))
                        query = query.Where(c => c.Special.Name.Contains(queryCond.SpecialName));
                }
                return query;
            };

        }
        /// <summary>
        /// 验证是否是专线在使用
        /// </summary>
        /// <param name="sysLoginUserId"></param>
        private User ValidIsSpecial(int sysLoginUserId)
        {
            var user = this._userRepository.GetModel().Include(c => c.Special).Where(c => c.ID == sysLoginUserId).SingleOrDefault();
            if (user == null)
                throw new DataOperationPermissions("用户无权限访问该资源，请求失败");
            //超级管理员可以使用
            if ((int)user.Type == 0)
                return user;
            if (user.Type != UserType.SpecialLine || user.Special == null)
            { throw new DataOperationPermissions("非专线不能使用该功能"); }
            return user;
        }
        /// <summary>
        /// 验证是否是分社在使用
        /// </summary>
        /// <param name="sysLoginUserId"></param>
        private User ValidIsBranch(int sysLoginUserId)
        {
            var user = this._userRepository.GetModel().Include(c => c.Branch).Where(c => c.ID == sysLoginUserId).SingleOrDefault();
            if (user == null)
                throw new DataOperationPermissions("用户无权限访问该资源，请求失败");
            //超级管理员可以使用
            if ((int)user.Type == 0)
                return user;
            if (user.Type != UserType.Branch || user.Branch == null)
            { throw new DataOperationPermissions("非分社不能使用该功能"); }
            return user;
        }
        #endregion

        /// <summary>
        /// 付款信息 列表
        /// </summary>
        /// <param name="queryCond"></param>
        /// <returns></returns>
        public CustomPagedList<PaymentViewModel> ApplyList(PagedParam<PaymentQuery> queryCond)
        {
            #region valid
            var user = this.ValidIsSpecial(queryCond.QueryDto.Sys_LoginUserID);
            #endregion

            //排序
            List<OrderDto> order = new List<OrderDto>();
            order.Add(new OrderDto() { OrderField = "ApplicationTime", OrderSort = "desc" });
            queryCond.OrderListDto = order;

            //超级管理员可以查询所有数据
            if ((int)user.Type == 0)
            {
                var tmp = this._paymentRepository.GetModel()
                                 .Include(c => c.Special)
                                 .GetPagedList(queryCond.PageDto.PageNo, queryCond.PageDto.PageSize,
                                 BuildQueryCondition(queryCond.QueryDto),
                                 queryCond.SortField).ToCustomPagedList<Payment, PaymentViewModel>((u) =>
                                 {
                                     var s = new PaymentViewModel()
                                     {
                                         ID = u.ID,
                                         SpecialId = u.Special.ID,
                                         SpecialName = u.Special.Name,
                                         Payee = u.Payee,
                                         Money = u.Money,
                                         Status = u.Status,
                                         ApplicationTime = u.ApplicationTime,
                                         AuditTime = u.AuditTime
                                     };
                                     return s;
                                 });
                return tmp;
            }
            else
            {
                var tmp = this._paymentRepository.GetModel()
                .Include(c => c.Special)
                .Where(c => c.SpecialId == user.Special.ID)
                .GetPagedList(queryCond.PageDto.PageNo, queryCond.PageDto.PageSize,
                BuildQueryCondition(queryCond.QueryDto),
                queryCond.SortField).ToCustomPagedList<Payment, PaymentViewModel>((u) =>
                {
                    var s = new PaymentViewModel()
                    {
                        ID = u.ID,
                        SpecialId = u.Special.ID,
                        SpecialName = u.Special.Name,
                        Payee = u.Payee,
                        Money = u.Money,
                        Status = u.Status,
                        ApplicationTime = u.ApplicationTime,
                        AuditTime = u.AuditTime
                    };
                    return s;
                });
                return tmp;
            }
        }

        /// <summary>
        /// 申请付款之前
        /// 获取专线相关信息
        /// </summary>
        /// <param name="id">专线id</param>
        /// <returns></returns>
        public PaymentApplyBeforeViewModel ApplyBeforeGet(int id)
        {
            if (id <= 0)
                throw new DataValidationException("请传入专线ID");

            var single = this._specialMainRepository.GetModel().Include(c => c.Branch).Where(c => c.ID == id).SingleOrDefault();
            if (single == null)
                throw new BusinessException("专线不存在");

            PaymentApplyBeforeViewModel model = new PaymentApplyBeforeViewModel();
            model.Supplier = new List<PaymentApplyBeforeSupplierViewModel>();
            model.ID = single.ID;
            model.Name = single.Name;
            model.CounterFeeRate = single.Branch.CounterFeeRate;

            var list = this._contractRepository.GetModel().Include(c => c.SellerSupplier)
                .Where(c => c.SpecialId == id && (c.Status == ContractStatus.Normal || c.Status == ContractStatus.Renewal)).ToList();
            //供应商信息
            var supper = list.Where(c => c.Type == ContractType.Supplier).ToList();
            supper.ForEach((e) =>
            {
                if (e.SellerSupplier.Status)
                {
                    model.Supplier.Add(new PaymentApplyBeforeSupplierViewModel()
                    {
                        SupplierID = e.SellerSupplier.ID,
                        SupplierName = e.SellerSupplier.Name,
                        SupplierChargeName = e.SellerSupplier.ChargeName,
                        SupplierBank = e.SellerSupplier.Bank,
                        SupplierChargeBankNumber = e.SellerSupplier.ChargeBankNumber
                    });
                }
            });

            return model;
        }

        /// <summary>
        /// 专线欠票情况判定
        /// </summary>
        /// <remarks>
        /// 如果当前时间-最早的一次请款时间>专线欠票周期 就不允许请款
        /// </remarks>
        /// <param name="specialId">专线ID</param>
        /// <returns></returns>
        public bool ApplyBeforeValidateDebts(int specialId)
        {
            if (specialId <= 0)
                throw new DataValidationException("请传入专线ID");

            var single = this._specialMainRepository.GetModel().Include(c => c.Branch).Where(c => c.ID == specialId).SingleOrDefault();
            if (single == null)
                throw new BusinessException("专线不存在");

            //最早一次请款信息
            //需判定：
            //      1、未收票：付款申请已确认 收票信息为空
            //      2、已收票：付款申请已确认 收票信息待确认、已废弃
            var lastPaymentApply = this._paymentRepository.GetModel().
                Include(c => c.Special).
                Include(c => c.CollectInvoice).
                Where(c => c.Special.ID == specialId
                    && c.Status == PaymentStatus.HasPayment).ToList();

            var last = lastPaymentApply.
                 Where(c => c.CollectInvoice == null
                     || (c.CollectInvoice != null && c.CollectInvoice.Count(p => p.Status == CollectInvoiceStatus.Discard || p.Status == CollectInvoiceStatus.WaitVerify) > 0)
                     ).OrderBy(c => c.ApplicationTime).SingleOrDefault();

            if (last == null)
                return true;

            //计算欠款周期（天）
            TimeSpan dt = DateTime.Now - last.ApplicationTime;
            if (dt.TotalDays > single.Branch.OweTicketsDay)
                return false;
            return true;
        }

        /// <summary>
        /// 申请付款
        /// </summary>
        /// <param name="model"></param>
        public void ToApplyPayment(PaymentApplyViewModel model)
        {
            #region valid
            var user = this.ValidIsSpecial(model.Sys_LoginUserID);
            if (model.SupplierID <= 0)
                throw new DataValidationException("请选择供应商");
            if (model.IsEntrust)
            {
                if (string.IsNullOrWhiteSpace(model.Payee))
                    throw new DataValidationException(string.Format(BusinessResourceMessage.PleaseInput, "收款人姓名"));
                else
                    if (!model.Payee.ValidateLen(20))
                        throw new DataValidationException("收款人姓名长度在1-20个字符");

                if (string.IsNullOrWhiteSpace(model.BankNumber))
                    throw new DataValidationException(string.Format(BusinessResourceMessage.PleaseInput, "收款人银行帐号"));
                else
                    if (!model.BankNumber.ValidateLen(20))
                        throw new DataValidationException("收款人银行帐号长度在1-20个字符");

                if (string.IsNullOrWhiteSpace(model.CollectionBank))
                    throw new DataValidationException(string.Format(BusinessResourceMessage.PleaseInput, "银行名称"));
                else
                    if (!model.CollectionBank.ValidateLen(30))
                        throw new DataValidationException("银行名称长度在1-30个字符");

                if (model.EntrustAttachments == null || model.EntrustAttachments.Count() <= 0)
                    throw new DataValidationException("请上传委托附件");
                if (model.CounterFee <= 0)
                    throw new DataValidationException(string.Format(BusinessResourceMessage.PleaseInput, "付款手续费"));
            }
            if (model.Moeny <= 0)
                throw new DataValidationException(string.Format(BusinessResourceMessage.PleaseInput, "付款金额"));

            var supplier = this._sellerSupplierRepository.GetModel().Where(c => c.ID == model.SupplierID).SingleOrDefault();
            if (supplier == null)
                throw new DataValidationException("供应商不存在");
            if (!supplier.Status)
                throw new DataValidationException("供应商状态异常");
            #endregion

            //付款信息
            var payment = new Payment()
            {
                SpecialId = user.Special.ID,
                SupplyId = model.SupplierID,
                Type = PaymentType.General,
                Status = PaymentStatus.WaitVerify,
                Payee = supplier.ChargeName,
                CollectionBank = supplier.Bank,
                BankNumber = supplier.ChargeBankNumber,
                Money = model.Moeny,
                ApplicantId = user.ID,
                ApplicationTime = DateTime.Now,
                SpecialName = user.Special.Name,
                ApplicantName = user.Name
            };

            //委托付款
            if (model.IsEntrust)
            {
                payment.Type = PaymentType.Entrust;
                payment.CounterFee = model.CounterFee;
                payment.PaymentEntrust = new List<PaymentEntrust>();
                payment.PaymentEntrust.Add(new PaymentEntrust()
                {
                    Payee = model.Payee,
                    CollectionBank = model.CollectionBank,
                    BankNumber = model.BankNumber,
                    Attachments = new List<Attachment>()
                });
                model.EntrustAttachments.ForEach((e) =>
                {
                    payment.PaymentEntrust[0].Attachments.Add(new Attachment()
                    {
                        Address = e.Item2,
                        CreateTime = DateTime.Now,
                        Name = e.Item1,
                        Type = AttachmentType.PaymentDelegateAttachment,
                        Suffix = e.Item1.Substring(e.Item1.LastIndexOf('.'), e.Item1.Length - e.Item1.LastIndexOf('.'))
                    });
                });
            }

            //计算付款手续费 付款手续费=付款金额*付款手续费率
            var special = this._specialMainRepository.GetModel().Include(c => c.Branch).Include(c => c.SpecialCapital).Where(c => c.ID == user.Special.ID).SingleOrDefault();
            string cf = string.Format("{0:F2}", model.Moeny * (special.Branch.CounterFeeRate / 100));
            payment.CounterFee = decimal.Parse(cf);

            //如果付款金额加上付款手续费大于余额减掉毛利就不能提交申请
            var payMoney = model.Moeny + model.CounterFee;
            var balance = special.SpecialCapital.Balance - special.SpecialCapital.Profit;
            if (payMoney > balance)
                throw new BusinessException("余额不足,无法申请付款");

            //需检查专线欠票情况，如果当前时间-最早的一次请款时间>专线欠票周期 就不允许请款
            if (!this.ApplyBeforeValidateDebts(user.Special.ID))
                throw new BusinessException("专线已欠票,无法申请付款");

            this._paymentRepository.Insert(payment);
        }

        /// <summary>
        /// 付款详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public PaymentDetailViewModel PaymentDetail(int id)
        {
            if (id <= 0)
                throw new DataValidationException("请选择付款信息");

            var tmp = this._paymentRepository.GetModel().Include(c => c.Special).Include(c => c.SellerSupplier).Include(c => c.PaymentEntrust.Select(s => s.Attachments)).Where(c => c.ID == id).SingleOrDefault();
            if (tmp == null)
                throw new BusinessException("付款信息不存在");

            PaymentDetailViewModel m = new PaymentDetailViewModel()
            {
                ID = tmp.ID,
                ApplicantName = tmp.ApplicantName,
                ApplicationTime = tmp.ApplicationTime,
                SpecialName = tmp.Special.Name,
                Money = tmp.Money,
                CounterFee = tmp.CounterFee,
                Status = tmp.Status,
                AuditName = tmp.AuditName,
                AuditTime = tmp.AuditTime,
                SerialNumber = tmp.SerialNumber,
                Remark = tmp.Remark,
                Type = tmp.Type,
                SupplierName = tmp.SellerSupplier.Name
            };
            //一般付款
            if (tmp.Type == PaymentType.General)
            {
                m.Payee = tmp.SellerSupplier.ChargeName;
                m.CollectionBank = tmp.SellerSupplier.Bank;
                m.BankNumber = tmp.SellerSupplier.ChargeBankNumber;
            }
            //委托付款
            else if (tmp.Type == PaymentType.Entrust)
            {
                m.Entrust_Payee = tmp.PaymentEntrust[0].Payee;
                m.Entrust_CollectionBank = tmp.PaymentEntrust[0].CollectionBank;
                m.Entrust_BankNumber = tmp.PaymentEntrust[0].BankNumber;
                m.Entrust_Attachment = new List<MyClass>();
                if (tmp.PaymentEntrust[0].Attachments != null)
                {
                    foreach (var item in tmp.PaymentEntrust[0].Attachments)
                    {
                        m.Entrust_Attachment.Add(new MyClass() { Item1 = item.Name, Item2 = item.Address });
                    }
                }
            }

            return m;
        }

        /// <summary>
        /// 付款管控 列表
        /// </summary>
        /// <param name="queryCond"></param>
        /// <returns></returns>
        public CustomPagedList<PaymentViewModel> ManageList(PagedParam<PaymentQuery> queryCond)
        {
            #region valid
            var user = this.ValidIsBranch(queryCond.QueryDto.Sys_LoginUserID);
            #endregion

            //排序
            List<OrderDto> order = new List<OrderDto>();
            order.Add(new OrderDto() { OrderField = "ApplicationTime", OrderSort = "desc" });
            queryCond.OrderListDto = order;

            //超级管理员可以查询所有数据
            if ((int)user.Type == 0)
            {
                var tmp = this._paymentRepository.GetModel()
                    .Include(c => c.Special)
                    .GetPagedList(queryCond.PageDto.PageNo, queryCond.PageDto.PageSize,
                    BuildQueryCondition(queryCond.QueryDto),
                    queryCond.SortField).ToCustomPagedList<Payment, PaymentViewModel>((u) =>
                    {
                        var s = new PaymentViewModel()
                        {
                            ID = u.ID,
                            SpecialId = u.Special.ID,
                            SpecialName = u.Special.Name,
                            Payee = u.Payee,
                            Money = u.Money,
                            Status = u.Status,
                            ApplicationTime = u.ApplicationTime,
                            AuditTime = u.AuditTime
                        };
                        return s;
                    });

                return tmp;
            }
            else
            {
                var tmp = this._paymentRepository.GetModel()
                                    .Include(c => c.Special)
                                    .Where(c => c.Special.BranchId == user.Branch.ID)//当前登录用户(分社)下的专线
                                    .GetPagedList(queryCond.PageDto.PageNo, queryCond.PageDto.PageSize,
                                    BuildQueryCondition(queryCond.QueryDto),
                                    queryCond.SortField).ToCustomPagedList<Payment, PaymentViewModel>((u) =>
                                    {
                                        var s = new PaymentViewModel()
                                        {
                                            ID = u.ID,
                                            SpecialId = u.Special.ID,
                                            SpecialName = u.Special.Name,
                                            Payee = u.Payee,
                                            Money = u.Money,
                                            Status = u.Status,
                                            ApplicationTime = u.ApplicationTime,
                                            AuditTime = u.AuditTime
                                        };
                                        return s;
                                    });

                return tmp;
            }
        }

        /// <summary>
        /// 确认
        /// </summary>
        /// <param name="model"></param>
        public void ToConfirmPayment(PaymentConAbaViewModel model)
        {
            #region valid
            var user = this.ValidIsBranch(model.Sys_LoginUserID);

            if (string.IsNullOrWhiteSpace(model.SerialNumber))
                throw new DataValidationException(string.Format(BusinessResourceMessage.PleaseInput, "银行流水号"));
            else
                if (!model.SerialNumber.ValidateLen(100))
                    throw new DataValidationException("银行流水号长度在1-100个字符");

            var single = this._paymentRepository.GetModelTracking().Include(c => c.Special).Where(c => c.ID == model.ID).SingleOrDefault();
            if (single == null)
                throw new BusinessException("付款信息不存在");
            if (single.Status == PaymentStatus.Discard)
                throw new BusinessException("付款信息已被废弃");
            if (single.Status == PaymentStatus.HasPayment)
                throw new BusinessException("付款信息已被确认");
            #endregion

            //如果付款金额加上付款手续费大于余额减掉毛利就不能付款
            var special = this._specialMainRepository.GetModelTracking().Include(c => c.SpecialCapital).Include(c => c.Branch).Where(c => c.ID == single.Special.ID).SingleOrDefault();
            var payMoney = single.Money + single.CounterFee;
            var balance = special.SpecialCapital.Balance - special.SpecialCapital.Profit;
            if (payMoney > balance)
                throw new BusinessException("专线余额不足,无法付款");

            //需检查专线欠票情况，如果当前时间-最早的一次请款时间>专线欠票周期 就不允许请款
            if (!this.ApplyBeforeValidateDebts(single.Special.ID))
                throw new BusinessException("专线已欠票,无法付款");

            single.SerialNumber = model.SerialNumber;
            single.Remark = model.Remark;
            single.Status = PaymentStatus.HasPayment;
            single.AuditTime = DateTime.Now;
            single.AuditId = user.ID;
            single.AuditName = user.Name;

            TransactionScopeNoMsdtc.UsingTransactionNoMsdtc(this._db, () =>
            {
                //增加资金池已付款（不要忘了付款手续费）
                special.SpecialCapital.Payment = special.SpecialCapital.Payment + payMoney;

                //查找机构下的'付款手续费'扣款类型ID
                var deduction = this._deductionRepository.GetModel().Where(c => c.BranchId == special.Branch.ID && c.Name == BusinessConst.PAYMENTFEENAME && c.Status).SingleOrDefault();
                if (deduction == null)
                    throw new BusinessException("未设置'付款手续费'扣款类型");

                //增加一条付款手续费的扣款记录
                Debit debit = new Debit()
                {
                    TypeId = deduction.ID,
                    PaymentId = single.ID,
                    SpecialId = single.Special.ID,
                    Money = payMoney,
                    Remark = single.Remark,
                    DebitorId = user.ID,
                    DebitorName = user.Name,
                    Time = DateTime.Now
                };

                this._paymentRepository.Update(single);
                this._specialMainRepository.Update(special);
                this._debitRepository.Insert(debit);
            });

        }

        /// <summary>
        /// 废弃
        /// </summary>
        /// <param name="model"></param>
        public void ToAbandonedPayment(PaymentConAbaViewModel model)
        {
            #region valid
            var user = this.ValidIsBranch(model.Sys_LoginUserID);

            if (!string.IsNullOrWhiteSpace(model.SerialNumber))
            {
                if (!model.SerialNumber.ValidateLen(100))
                    throw new DataValidationException("银行流水号长度在1-100个字符");
            }

            if (string.IsNullOrWhiteSpace(model.Remark))
                throw new DataValidationException(string.Format(BusinessResourceMessage.PleaseInput, "付款备注"));

            var single = this._paymentRepository.GetModelTracking().Where(c => c.ID == model.ID).SingleOrDefault();
            if (single == null)
                throw new BusinessException("付款信息不存在");
            if (single.Status == PaymentStatus.Discard)
                throw new BusinessException("付款信息已被废弃");
            #endregion

            single.SerialNumber = model.SerialNumber;
            single.Remark = model.Remark;
            single.Status = PaymentStatus.Discard;
            single.AuditTime = DateTime.Now;
            single.AuditId = user.ID;
            single.AuditName = user.Name;

            this._paymentRepository.Update(single);
        }

        /// <summary>
        /// 更新打印页面访问次数
        /// </summary>
        /// <param name="id"></param>
        public void ToUpdatePrintViewNum(int id)
        {
            if (id <= 0)
                throw new DataValidationException("请选择付款信息");

            var single = this._paymentRepository.GetModelTracking().Where(c => c.ID == id).SingleOrDefault();
            if (single == null)
                throw new BusinessException("付款信息不存在");

            single.PrintPreviewTimes = single.PrintPreviewTimes + 1;
            this._paymentRepository.Update(single);
        }

        /// <summary>
        /// 单据打印信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public PaymentPrintViewModel PrintDetail(int id, int operateUserId)
        {
            #region valid
            var user = this.ValidIsBranch(operateUserId);
            #endregion

            var single = this._paymentRepository.GetModelTracking().Include(c => c.Special).Include(c => c.SellerSupplier).Include(c => c.PaymentEntrust).Where(c => c.ID == id).SingleOrDefault();
            if (single == null)
                throw new BusinessException("付款信息不存在");

            PaymentPrintViewModel tmp = new PaymentPrintViewModel()
            {
                ID = single.ID,
                BarCodeHeader = PRINTBARCODEHEADER,
                BarCode = this.DateTimeStr(DateTime.Now),//生成条形码
                PrintNumberOf = single.PrintPreviewTimes,
                PaySpecialName = single.Special.Name,
                PaySpecialChargeName = single.Special.ChargeName,
                HandlingName = user.Name,
                Money = single.Money,
                MoneyString = CommonMethod.GetInstance.GetRMBString(single.Money.ToString()),
                PayTime = single.AuditTime,
                SerialNumber = single.SerialNumber
            };
            //一般付款
            if (single.Type == PaymentType.General)
            {
                tmp.Payee = single.Payee;
                tmp.CollectionBank = single.CollectionBank;
                tmp.BankNumber = single.BankNumber;
            }
            //委托付款
            else if (single.Type == PaymentType.Entrust)
            {
                tmp.Payee = single.PaymentEntrust[0].Payee;
                tmp.CollectionBank = single.PaymentEntrust[0].CollectionBank;
                tmp.BankNumber = single.PaymentEntrust[0].BankNumber;
            }

            return tmp;
        }

        private string C(int value, int max = 10)
        {
            return value >= max ? value.ToString() : (max == 10 ? "0" : (value >= 10 ? "0" : "00")) + value;
        }
        private string DateTimeStr(DateTime dt)
        {
            string str = dt.Year.ToString()
                + this.C(dt.Month)
                + this.C(dt.Day)
                + this.C(dt.Hour)
                + this.C(dt.Minute)
                + this.C(dt.Second)
                + this.C(dt.DayOfYear, 100)
                + this.C(dt.Millisecond, 100);
            return str;
        }
    }
}
